package com.hzcx.app.simplechat.ui.home.adapter;

import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.util.DateUtils;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.util.ChatNoticeUtil;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.model.PublicModel;
import com.hzcx.app.simplechat.ui.chat.bean.ChatCustomNoticeBean;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.litepal.LitePal;

import java.util.Date;
import java.util.List;

public class HomeMessageAdapter extends BaseQuickAdapter<EMConversation, BaseViewHolder> {


    public HomeMessageAdapter(int layoutResId, @Nullable List<EMConversation> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, EMConversation item) {

        // 设置昵称，头像
        EMMessage message = item.getLastMessage();
        final HxUserInfoBean[] userInfoBean = new HxUserInfoBean[1];
//        final GroupInfoBean[] groupInfoBean = new GroupInfoBean[1];
        if (message.getChatType() == EMMessage.ChatType.Chat) { // 单聊
            String hxusername;
            if (message.direct() == EMMessage.Direct.SEND) {
                hxusername = message.getTo();
            } else {
                hxusername = message.getFrom();
            }
            LitePal.where("hxusername=? and myUserId=?", hxusername, UserInfoUtil.getUserId() + "").findFirstAsync(HxUserInfoBean.class).listen(hxUserInfoBean -> {
                if (hxUserInfoBean == null) {
                    PublicModel.getUserInfoByHx(mContext, hxusername, new BaseObserver<HxUserInfoBean>() {
                        @Override
                        protected void onSuccess(HxUserInfoBean data) {
                            data.setHxusername(hxusername);
                            data.setMyUserId(UserInfoUtil.getUserId());
                            data.save();
                            userInfoBean[0] = data;
                            GlideUtils.loadImg(mContext, data.getAvatar(), helper.getView(R.id.iv_head));
                            if (EmptyUtils.isNotEmpty(data.getRemarks_name())) {
                                helper.setText(R.id.tv_nick_name, data.getRemarks_name());
                            } else {
                                helper.setText(R.id.tv_nick_name, data.getNickname());
                            }
                        }
                    });
                } else {
                    userInfoBean[0] = hxUserInfoBean;
                    GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                    if (EmptyUtils.isNotEmpty(hxUserInfoBean.getRemarks_name())) {
                        helper.setText(R.id.tv_nick_name, hxUserInfoBean.getRemarks_name());
                    } else {
                        helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                    }
                }
            });
        } else if (message.getChatType() == EMMessage.ChatType.GroupChat) { // 群聊
            String hxusername = message.getTo();
            helper.setText(R.id.tv_nick_name, "");
            LitePal.where("hx_groupid=?", hxusername).findFirstAsync(GroupInfoBean.class).listen(groupInfoBean -> {
                if (groupInfoBean == null) {
                    GroupModel.getHxGroupInfo(mContext, hxusername, new BaseObserver<GroupInfoBean>() {
                        @Override
                        protected void onSuccess(GroupInfoBean data) {
                            GroupModel.getGroupInfo(mContext, data.getGroup_id(), new BaseObserver<GroupInfoBean>() {
                                @Override
                                protected void onSuccess(GroupInfoBean data) {
                                    Log.e("home_message_list", "GroupInfoBean: " + data.toString());
                                    data.setMembersCount(data.getMembers().size());
                                    data.save();
                                    GroupInfoBeanLiveData.update(data);
                                    HxUserInfoBean hxUserInfoBean = HxUserInfoBean.HxUserInfoBean(data);
                                    userInfoBean[0] = hxUserInfoBean;
                                    GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                                    helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                                }
                            });
                        }
                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                        }
                    });
                } else {
                    HxUserInfoBean hxUserInfoBean = HxUserInfoBean.HxUserInfoBean(groupInfoBean);
                    userInfoBean[0] = hxUserInfoBean;
                    GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                    helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                }
            });
        } else { // room
//            String hxusername = message.getTo();
//            LitePal.where("hx_groupid=? and myUserId=?", hxusername, UserInfoUtil.getUserId() + "").findFirstAsync(GroupInfoBean.class).listen(hxGroupInfoBean -> {
//                if (hxGroupInfoBean == null) {
//
//                } else {
//                    userInfoBean[0] = HxUserInfoBean.HxUserInfoBean(hxGroupInfoBean);
//                    helper.setText(R.id.tv_nick_name, hxGroupInfoBean.getGroup_name());
//                    GlideUtils.loadImg(mContext, hxGroupInfoBean.getGroup_image(), helper.getView(R.id.iv_head));
//                }
//            });
        }

        // 设置内容
        if (message.getType() == EMMessage.Type.TXT) {
            EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
            helper.setText(R.id.tv_content, txtBody.getMessage());
        } else if (message.getType() == EMMessage.Type.VOICE) {
            helper.setText(R.id.tv_content, "[语音消息]");
        } else if (message.getType() == EMMessage.Type.IMAGE) {
            helper.setText(R.id.tv_content, "[图片]");
        } else if (message.getType() == EMMessage.Type.LOCATION) {
            helper.setText(R.id.tv_content, "[位置]");
        } else if (message.getType() == EMMessage.Type.CUSTOM) {
            EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_SHARE)) {
                helper.setText(R.id.tv_content, "[个人名片]");
            } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_RECALL)) {
                if (message.direct() == EMMessage.Direct.SEND) {
                    helper.setText(R.id.tv_content, "您撤回了一条消息");
                } else {
                    helper.setText(R.id.tv_content, "对方撤回了一条消息");
                }
            } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_BLACK)) {
                helper.setText(R.id.tv_content, "对方拒收了您的消息");
            } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_DELETE)) {
                helper.setText(R.id.tv_content, "对方开启了朋友验证，请先发送验证请求，对方通过后才能聊天");
            } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_ASSISTANT)) {
                helper.setText(R.id.tv_content, "[官方消息]");
            } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_NOTICE)) {
                try {
                    String data = message.getStringAttribute("notice_data");
                    ChatCustomNoticeBean bean = new Gson().fromJson(data, ChatCustomNoticeBean.class);
                    helper.setText(R.id.tv_content, bean.getNotice_title());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)){
                helper.setText(R.id.tv_content,"[图片]");
            } else if(customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){
                helper.setText(R.id.tv_content,"[视频]");
            }else {
                helper.setText(R.id.tv_content, "[未知消息]");
            }
        } else {
            helper.setText(R.id.tv_content, "[未知消息]");
        }

        // 时间
        helper.setText(R.id.tv_date, DateUtils.getTimestampString(new Date(message.getMsgTime())));
        // 设置未读数量
        helper.setText(R.id.tv_num, String.valueOf(item.getUnreadMsgCount()));
        if (item.getUnreadMsgCount() > 0) {
            helper.setVisible(R.id.tv_num, true);
        } else {
            helper.setVisible(R.id.tv_num, false);
        }

        //会员才有已读未读
        if(UserInfoUtil.getUserIsVip()) {
            // 设置已读未读状态
            if (helper.getView(R.id.iv_read) != null) {
                if (message.isAcked()) {
                    helper.setVisible(R.id.iv_read, true);
                } else {
                    helper.setVisible(R.id.iv_read, false);
                }
            }
        }else {
            helper.setVisible(R.id.iv_read, false);
        }


        if (message.isUnread()) {
            helper.setText(R.id.tv_msg, "标为\n已读");
        } else {
            helper.setText(R.id.tv_msg, "标为\n未读");
        }

        if (item.getExtField().equals("toTop")) {
            helper.setText(R.id.tv_to_top, "取消置顶");
        } else {
            helper.setText(R.id.tv_to_top, "置顶");
        }

        helper.addOnClickListener(R.id.cons_content);

        // 标记未读
        helper.getView(R.id.tv_msg).setOnClickListener(view -> {
            if (message.isUnread()) {
                item.markAllMessagesAsRead();
            } else {
                message.setUnread(true);
                item.updateMessage(message);
            }
            notifyDataSetChanged();
            if (listener != null) {
                listener.readChange(helper.getAdapterPosition() - 1);
            }
        });

        // 删除会话
        helper.getView(R.id.tv_delete).setOnClickListener(view -> {
            if (message.direct() == EMMessage.Direct.SEND) {
                EMClient.getInstance().chatManager().deleteConversation(message.getTo(), false);
            } else {
                EMClient.getInstance().chatManager().deleteConversation(message.getFrom(), false);
            }
            mData.remove(helper.getAdapterPosition() - 1);
            notifyDataSetChanged();
            if (listener != null) {
                listener.delete(helper.getAdapterPosition() - 1);
            }
        });

        // 置顶
        helper.getView(R.id.tv_to_top).setOnClickListener(view -> {
            if (listener != null) {
                listener.toTop(helper.getAdapterPosition() - 1);
            }
        });

        // 列表点击
        helper.getView(R.id.cons_content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userInfoBean[0] == null) {
                    ToastUtils.show("用户数据异常，请稍后重试");
                    return;
                }
                if (message.getChatType() == EMMessage.ChatType.Chat) {
                    ChatUtil.getInstance().toChatUi(mContext, userInfoBean[0]);
                } else {
                    ChatUtil.getInstance().toGroupChatUi(mContext, userInfoBean[0]);
                }
                ChatNoticeUtil.getInstance(mContext).clearNotice(message);
            }
        });
    }


    public interface OnHomeMessageListener {
        void delete(int pos);

        void readChange(int pos);

        void toTop(int pos);
    }

    private OnHomeMessageListener listener;

    public void setOnHomeMessageListener(OnHomeMessageListener listener) {
        this.listener = listener;
    }
}
